<template>
  <router-view v-slot="{ Component, route }">
    <transition :name="'fade-' + (direction === 'forward' ? 'in' : 'out')" v-if="isTransition">
      <keep-alive :include="keepAliveNameList">
        <component :is="Component" :key="route.path" />
      </keep-alive>
    </transition>
    <transition v-else>
      <keep-alive :include="keepAliveNameList">
        <component :is="Component" :key="route.path" />
      </keep-alive>
    </transition>
  </router-view>
</template>
<script setup>
import { computed, ref } from 'vue';
import router from '@/router';
import { storeToRefs } from 'pinia';
import { userStore } from '@/stores/userStore';

const { direction } = storeToRefs(userStore());
// 是否加入缓存
const keepAliveNameList = computed(() => {
  let list = router.getRoutes();
  let keepAliveList = [];
  list.forEach((item) => {
    if (item.meta.isKeepAlive) {
      keepAliveList.push(item.name);
    }
  });
  return keepAliveList;
});

const isTransition = ref(true);
// tabbar中路由无需动画
router.beforeEach((to, from) => {
  if (
    ['home', 'category', 'find', 'cart', 'user'].includes(to.name) &&
    ['home', 'category', 'find', 'cart', 'user', undefined].includes(from.name)
  ) {
    isTransition.value = false;
  } else {
    isTransition.value = true;
  }
});
</script>
<style>
.fade-out-enter-active,
.fade-out-leave-active,
.fade-in-enter-active,
.fade-in-leave-active {
  will-change: transform;
  transition: all 250ms;
  height: 100%;
  top: 0;
  position: absolute;
  backface-visibility: hidden;
  perspective: 1000;
}

.fade-out-enter-from {
  opacity: 0;
  transform: translate3d(-100%, 0, 0);
}

.fade-out-leave-to {
  opacity: 0;
  transform: translate3d(100%, 0, 0);
}

.fade-in-enter-from {
  opacity: 0;
  transform: translate3d(100%, 0, 0);
}

.fade-in-leave-to {
  opacity: 0;
  transform: translate3d(-100%, 0, 0);
}
</style>
